﻿// See https://aka.ms/new-console-template for more information

//Socket连接服务器

using System.Net.Sockets;
using System.Net.WebSockets;
using sgf.server;

public class Program
{
    public static async Task Main(string[] args)
    {
        TestSocket();
        // TestWebsocket();
        while (true)
        {
        }
    }

    private static async void TestSocket()
    {
        // Console.WriteLine("Hello World!");
        //创建一个Socket对象
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //连接到服务器
        await socket.ConnectAsync("127.0.0.1", 4040);
        var msg = Message.CreateMessage(new AddAccount
        {
            account = "123213"
        });
        //toBytes
        // var bytes = BsonHelper.ToBson(msg);
        await socket.SendAsync(msg.ToBytes(), SocketFlags.None);
    }

    private static async void TestWebsocket()
    {
        // //创建一个Socket对象
        var webSocket = new ClientWebSocket();
        await webSocket.ConnectAsync(new Uri("ws://127.0.0.1:4041/ws"), CancellationToken.None);
        // var bytes = new ArraySegment<Byte>();
        // await webSocket.ReceiveAsync(bytes, CancellationToken.None);
        // var msg = BsonHelper.FromBson<Message>(Encoding.UTF8.GetString(bytes));
        var msg = Message.CreateMessage(new AddAccount
        {
            account = "9999"
        });
        //toBytes
        // var bytes = BsonHelper.ToBson(msg);
        // BsonHelper.FromBson<Message>(bytes);

        await webSocket.SendAsync(msg.ToBytes(), WebSocketMessageType.Binary, true, CancellationToken.None);
    }
}